package com.orange.cetback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.orange.cetback.common.context.BaseContext;
import com.orange.cetback.common.vo.PageResult;
import com.orange.cetback.pojo.dto.MedalLevelDTO;
import com.orange.cetback.pojo.entity.MedalLevel;
import com.orange.cetback.mapper.MedalLevelMapper;
import com.orange.cetback.pojo.entity.User;
import com.orange.cetback.pojo.entity.UserMedal;
import com.orange.cetback.service.MedalLevelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orange.cetback.service.UserMedalService;
import com.orange.cetback.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenenjun
 * @since 2025-04-02
 */
@Service
public class MedalLevelServiceImpl extends ServiceImpl<MedalLevelMapper, MedalLevel> implements MedalLevelService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMedalService userMedalService;

    @Override
    public PageResult<MedalLevel> pageQuery(MedalLevelDTO medalLevelDTO) {
        Page<MedalLevel> page = new Page<>(medalLevelDTO.getPageNum(), medalLevelDTO.getPageSize());
        LambdaQueryWrapper<MedalLevel> wrapper = new LambdaQueryWrapper<>();
        if (medalLevelDTO.getMedalName() != null) {
            wrapper.like(MedalLevel::getMedalName, medalLevelDTO.getMedalName());
        }
        this.baseMapper.selectPage(page, wrapper);
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    @Override
    public MedalLevel checkAndGrantMedals() {
        User user = userService.getById(BaseContext.getCurrentId());
        LambdaQueryWrapper<MedalLevel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MedalLevel::getRequiredIntegral, user.getIntegral());
        MedalLevel medalLevel = this.baseMapper.selectOne(wrapper);
        if(medalLevel != null){
            userMedalService.save(UserMedal.builder()
                            .medalId(medalLevel.getMedalId())
                            .userId(user.getId())
                            .obtainTime(LocalDateTime.now())
                            .build());
        }
        return medalLevel;
    }
}
